import { Injectable } from '@angular/core';
import { CookiesService } from './../cookies/cookies.service';
import { UtilsService } from '../utils/utils.service';


@Injectable()
export class FetchRequestService {

  private utilsService = new UtilsService();
  private cookie = new CookiesService(document);

  private header = {
    'Content-Type': 'application/json;charset=UTF-8'
  };

  constructor() {
    if (!self.fetch) {
      console.log('Current Browser Not Support Fetch API !!!');
      return;
    }
  }


  /**
   * Get请求
   * @param url string
   * @return Promise Object
   */
  public getRequest(url: string) {
    return fetch(url, {
      // credentials: 'include',
      // mode: 'no-cors',
    }).then(res => res.json()).catch(error => {
      // console.log(error);
      throw Error(error);
    });

  }

  /**
   * Post请求
   * @param url string
   * @param data Object
   * @return Promise Object
   */
  public postRequest(url: string, data: any) {
    return fetch(url, {
        // 携带Cookie, Access-Control-Allow-Origin不能为*且必须指定域
        // credentials: 'include',
        mode: 'cors',
        cache: 'default',
        headers: {
        // 'Content-Type': 'application/json'  //json传参
        'Accept': 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded',
        'user-name': this.cookie.getCookie('englishName') ? this.cookie.getCookie('englishName') : null
      },
      method: 'POST',
      body: this.utilsService.isObject(data) ? this.utilsService.encodeObject(data) : data,
    });
  }

  /**
   * 可传文件的POST请求
   * @param url , api url, string
   * @param data , FormData
   * @return Promise Object
   */
  public postRequestFile(url: string, data: FormData) {
    return fetch(url, {
      mode: 'cors', // mode 是 cors 跨域的话 不能加 headers
      cache: 'default',
      headers: {
      // 'Content-Type': 'application/json'  //json传参
      'Accept': 'application/json',
      // 'Content-Type': 'multipart/form-data' // 上传文件不需要此项, body里已经是FormData
      'user-name': this.cookie.getCookie('englishName') ? this.cookie.getCookie('englishName') : null
    },
    method: 'POST',
    body: data,
  });
  }

  public putRequest(url: string, data: Object) {}

  public deleteRequest(url: string, data: Object) {}


  public headerRequest(url: string) {}
}